package org.pyq.core.process;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.LoaderClassPath;

import java.lang.instrument.Instrumentation;

/**
 * @author pengYongQiang
 * @date 2022/1/7 18:19
 */
public class Test1Process extends AbsProcess {

    public Test1Process(Instrumentation instrumentation) {
        super("org.pyq.agent.Application", instrumentation);
    }

    @Override
    public byte[] invoke(String... s) {
        try {
            return doInvoke();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] doInvoke() throws Exception {

        Class<?> clazz = getClazz();
        String className = getClassName();
        ClassLoader classLoader = clazz.getClassLoader();

        ClassPool classPool = new ClassPool();
        LoaderClassPath loaderClassPath = new LoaderClassPath(classLoader);
        classPool.insertClassPath(loaderClassPath);

        String replace = className.replace("/", ".");
        CtClass cla = classPool.get(replace);
        CtClass[] params = {
                classPool.get("java.lang.String")
        };
        CtMethod ctMethod = cla.getDeclaredMethod("a", params);

        //ctMethod.insertBefore("org.pyq.agent.Demo.begin($$)");
        String src = "{System.out.println(\"你好啊444555！！！！！\");" +
                "demoService.demo();" +
                "return \"s -- \"+$1;" +
                "}";
        ctMethod.setBody(src);

        //  并不能引用局部变量
        //  ctMethod.insertAfter("s = \"nihao\";");

        //ctMethod.insertBefore(src);
        byte[] bytes = cla.toBytecode();
        classPool.removeClassPath(loaderClassPath);
        return bytes;
    }
}
